//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

#include <buola/buola.h>

#include <buola/algorithm/container.h>
#include <buola/io/cresourcefinder.h>
#include <buola/os/cenv.h>
#include <buola/algorithm/split.h>
#include <buola/io/cfolder.h>
#include <buola/io/filesystem.h>

namespace buola { namespace io {

CResourceFinder &data_finder()
{
    static CResourceFinder *lFinder=nullptr;

    if(!lFinder)
    {
        lFinder=new CResourceFinder;

        std::string lString=CEnv::Get("XDG_DATA_HOME");

        if(lString.length())
            lFinder->AddPath(CResourceFinder::SCOPE_USER,io::file(lString));
        else
            lFinder->AddPath(CResourceFinder::SCOPE_USER,io::get_home()/".local/share");

        lString=CEnv::Get("XDG_DATA_DIRS");

        if(lString.length())
        {
            std::vector<std::string> lStringList;
            split(lString,lStringList,fn::equal_to(':'),nDeleteEmpty);
            for(int i=0;i<lStringList.size();i++)
                lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file(lStringList[i]));
            lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file(BUOLA_SHARE_DIR));
        }
        else
        {
            lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file(BUOLA_SHARE_DIR));
            lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file("/usr/local/share"));
            lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file("/usr/share"));
        }

    }

    return *lFinder;
}

CResourceFinder &config_finder()
{
    static CResourceFinder *lFinder=nullptr;

    if(!lFinder)
    {
        lFinder=new CResourceFinder;

        std::string lString=CEnv::Get("XDG_CONFIG_HOME");

        if(lString.length())
            lFinder->AddPath(CResourceFinder::SCOPE_USER,io::file(lString));
        else
            lFinder->AddPath(CResourceFinder::SCOPE_USER,io::get_home()/".config");

        lString=CEnv::Get("XDG_CONFIG_DIRS");

        if(lString.length())
        {
            std::vector<std::string> lStringList;
            split(lString,lStringList,fn::equal_to(':'),nDeleteEmpty);
            for(int i=0;i<lStringList.size();i++)
                lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file(lStringList[i]));
        }
        else
        {
            lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file("/etc/xdg"));
        }
    }

    return *lFinder;
}

CResourceFinder &cache_finder()
{
    static CResourceFinder *lFinder=nullptr;

    if(!lFinder)
    {
        lFinder=new CResourceFinder;

        std::string lString=CEnv::Get("XDG_CACHE_HOME");

        if(lString.length())
            lFinder->AddPath(CResourceFinder::SCOPE_USER,io::file(lString));
        else
            lFinder->AddPath(CResourceFinder::SCOPE_USER,io::get_home()/".cache");
    }

    return *lFinder;
}

CResourceFinder &mime_finder()
{
    static CResourceFinder *lFinder=nullptr;

    if(!lFinder)
    {
        std::vector<std::string> lSubPaths={"mime"};
        lFinder=new CResourceFinder(data_finder(),lSubPaths);
        lFinder->AddExtension("xml");
    }

    return *lFinder;
}

CResourceFinder &icon_finder()
{
    static CResourceFinder *lFinder=nullptr;

    if(!lFinder)
    {
        std::vector<std::string> lSubPaths={"icons"};
        lFinder=new CResourceFinder(data_finder(),lSubPaths);
        lFinder->AddExtension("png");
        lFinder->AddExtension("xpm");
        lFinder->AddPath(CResourceFinder::SCOPE_SYSTEM,io::file("/usr/share/pixmaps"));
    }

    return *lFinder;
}

CResourceFinder &registry_finder()
{
    static CResourceFinder *lFinder=nullptr;

    if(!lFinder)
    {
        std::vector<std::string> lSubPaths={"buola/registry"};
        lFinder=new CResourceFinder(data_finder(),lSubPaths);
    }

    return *lFinder;
}

CResourceFinder::CResourceFinder()
{
}

CResourceFinder::CResourceFinder(const CResourceFinder &pBase,const std::vector<std::string> &pSubPaths)
{
    for(int i=0;i<pBase.mPaths.size();i++)
    {
        SPath lPath;
        lPath.mScope=pBase.mPaths[i].mScope;

        for(int j=0;j<pSubPaths.size();j++)
        {
            lPath.mPath=pBase.mPaths[i].mPath/pSubPaths[j];
            mPaths.push_back(lPath);
        }
    }
}

CResourceFinder::~CResourceFinder()
{
}

void CResourceFinder::AddPath(EScope pScope,const io::CURI &pPath)
{
    for(int i=0;i<mPaths.size();i++)
    {
        if(mPaths[i].mScope==pScope&&mPaths[i].mPath==pPath)
            return;
    }

    SPath lPath;
    lPath.mScope=pScope;
    lPath.mPath=pPath;

    mPaths.push_back(lPath);
}

void CResourceFinder::AddExtension(const std::string &pExtension)
{
    mExtensions.push_back(pExtension);
}

io::CURI CResourceFinder::FindFolder(const std::string &pName,EOptions pOptions)
{
    //if it's an absolute path, try finding it by itself
    if(pName[0]=='/'&&pOptions&MAYBE_ABSOLUTE)
    {
        if(is_folder(io::file(pName)))
            return io::file(pName);
    }

    //try first in general prefixes, under every subpath and with
    //every extension
    for(int i=0;i<mPaths.size();i++)        //all paths
    {
        if(pOptions&USER_ONLY&&mPaths[i].mScope!=SCOPE_USER) continue;
        io::CURI lURI=mPaths[i].mPath/pName;

        if(is_folder(lURI))
            return lURI;

        for(int j=0;j<mExtensions.size();j++)
        {
            lURI=mPaths[i].mPath/(pName+"."+mExtensions[j]);
            if(is_folder(lURI))
                return lURI;
        }
    }

    if(pOptions&CREATE)
    {
        io::mkdir(mPaths[0].mPath/pName);
        return mPaths[0].mPath/pName;
    }

    return io::CURI();
}

std::vector<io::CURI> CResourceFinder::FindFolders(const std::string &pName,EOptions pOptions)
{
    std::vector<io::CURI> lResult;

    //if it's an absolute path, try finding it by itself
    if(pName[0]=='/'&&pOptions&MAYBE_ABSOLUTE)
    {
        if(is_folder(io::file(pName)))
        {
            lResult.push_back(io::file(pName));
            return lResult;
        }
    }

    //try first in general prefixes, under every subpath and with
    //every extension
    for(int i=0;i<mPaths.size();i++)        //all paths
    {
        if(pOptions&USER_ONLY&&mPaths[i].mScope!=SCOPE_USER) continue;
        io::CURI lURI=mPaths[i].mPath/pName;

        if(is_folder(lURI))
            lResult.push_back(lURI);

        for(int j=0;j<mExtensions.size();j++)
        {
            lURI=mPaths[i].mPath/(pName+"."+mExtensions[j]);
            if(is_folder(lURI))
                lResult.push_back(lURI);
        }
    }

    if(lResult.empty()&&pOptions&CREATE)
    {
        io::mkdir(mPaths[0].mPath/pName);
        lResult.push_back(mPaths[0].mPath/pName);
    }

    return lResult;
}

io::CURI CResourceFinder::FindFile(const std::string &pName,EOptions pOptions)
{
    //if it's an absolute path, try finding it by itself
    if(pName[0]=='/'&&pOptions&MAYBE_ABSOLUTE)
    {
        if(exists(io::file(pName)))
            return io::file(pName);
    }

    //try first in general prefixes, under every subpath and with
    //every extension
    for(int i=0;i<mPaths.size();i++)        //all paths
    {
        if(pOptions&USER_ONLY&&mPaths[i].mScope!=SCOPE_USER) continue;
        io::CURI lURI=mPaths[i].mPath/pName;

        if(exists(lURI))
            return lURI;

        for(int j=0;j<mExtensions.size();j++)
        {
            lURI=mPaths[i].mPath/(pName+"."+mExtensions[j]);
            if(exists(lURI))
                return lURI;
        }
    }

    if(pOptions&CREATE)
    {
        io::mkdir((mPaths[0].mPath/pName).GetParent());
        return mPaths[0].mPath/pName;
    }

    return io::CURI();
}

std::vector<io::CURI> CResourceFinder::FindFiles(const std::string &pName,EOptions pOptions)
{
    std::vector<io::CURI> lResult;

    //if it's an absolute path, try finding it by itself
    if(pName[0]=='/'&&pOptions&MAYBE_ABSOLUTE)
    {
        if(exists(io::file(pName)))
        {
            lResult.push_back(io::file(pName));
            return lResult;
        }
    }

    //try first in general prefixes, under every subpath and with
    //every extension
    for(int i=0;i<mPaths.size();i++)        //all paths
    {
        if(pOptions&USER_ONLY&&mPaths[i].mScope!=SCOPE_USER) continue;
        io::CURI lURI=mPaths[i].mPath/pName;

        if(exists(lURI))
            lResult.push_back(lURI);

        for(int j=0;j<mExtensions.size();j++)
        {
            lURI=mPaths[i].mPath/(pName+"."+mExtensions[j]);
            if(exists(lURI))
                lResult.push_back(lURI);
        }
    }

    if(lResult.empty()&&pOptions&CREATE)
    {
        io::mkdir((mPaths[0].mPath/pName).GetParent());
        lResult.push_back(mPaths[0].mPath/pName);
    }

    return lResult;
}

/*namespace io*/ } /*namespace buola*/ }
